import express from 'express';
import sql from '../../sql.js';
const router = express.Router();

// 查询日记接口
router.post('/searchDiary', async (req, res) => {
    const diaryId = req.body.diaryId;
    const keyword = req.body.keyword;
    let page = parseInt(req.body.page) || 1;
    const pageSize = parseInt(req.body.pageSize) || 10;
    let diaries;

    // 构建查询基础部分
    let query = 'SELECT d.*, ';
    query += '(SELECT JSON_ARRAYAGG(JSON_OBJECT(\'ID\', c.ID, \'user_id\', c.user_id, \'type\', c.type, \'create_time\', c.create_time, \'content\', c.content, \'report\', c.report, \'is_read\', c.is_read)) FROM comment c WHERE c.diary_id = d.ID) AS comments ';
    query += 'FROM diary d ';
    let whereClauses = [];
    let values = [];


    // 根据参数添加条件
    if (diaryId) {
        whereClauses.push('d.ID =?');
        values.push(diaryId);
    }
    if (keyword) {
        whereClauses.push('(d.title LIKE? OR d.content LIKE?)');
        values.push(`%${keyword}%`, `%${keyword}%`);
    }

    if (whereClauses.length > 0) {
        query += ' WHERE ' + whereClauses.join(' AND ');
    }

    // 分页
    query += ' LIMIT ?, ?';
    values.push((page - 1) * pageSize, pageSize);

    // 计算总数
    const countQuery = `SELECT COUNT(*) AS totalCount FROM diary as d ${whereClauses.length > 0? ' WHERE ' + whereClauses.join(' AND ') : ''}`;
    const [countResult] = await sql.query(countQuery, values);
    const totalCount = countResult[0].totalCount;
    const totalPages = Math.ceil(totalCount / pageSize);
    
    try {
        [diaries] = await sql.query(query, values);
        if (diaries.length === 0 && page > 1) {
            page = page - 1;
            values[values.length-2] = (page - 1) * pageSize;
            const [data] = await sql.query(query, values);
            diaries = data;
        }
        res.send({
            status: 'success',
            message: '日记查询成功',
            data: diaries,
            pagination: {
                currentPage: page,
                pageSize: pageSize,
                totalCount: totalCount,
                totalPages: totalPages
            }
        });
    } catch (error) {
        console.error('查询错误：', error);
        res.send({
            status: 'error',
            message: '服务器内部错误',
            errorCode: 500
        });
    }
});

// 新建日记接口
router.post('/addDiary', async (req, res) => {
    const { title, image, content, weather_id, weather_name, mood } = req.body;
    try {
        const query = 'INSERT INTO diary (title, image, content, weather_id, weather_name, mood) VALUES (?,?,?,?,?,?)';
        const values = [title, image, content, weather_id, weather_name, mood];
        await sql.query(query, values);

        // 获取刚插入的日记数据
        const selectQuery = 'SELECT * FROM diary WHERE ID = LAST_INSERT_ID()';
        const [newDiary] = await sql.query(selectQuery);
        res.send({
            status: 'success',
            message: '日记创建成功',
            diary: newDiary[0]
        });
    } catch (error) {
        console.error('创建日记错误：', error);
        res.send({
            status: 'error',
            message: '服务器内部错误',
            errorCode: 500
        });
    }
});

// 删除日记接口
router.delete('/deleteDiary/:diaryId', async (req, res) => {
    const diaryId = req.params.diaryId;
    try {
        const query = 'DELETE FROM diary WHERE ID =?';
        await sql.query(query, [diaryId]);
        res.send({
            status: 'success',
            message: '日记删除成功'
        });
    } catch (error) {
        console.error('删除日记错误：', error);
        res.send({
            status: 'error',
            message: '服务器内部错误',
            errorCode: 500
        });
    }
});

export default router;

